/**
 * Created by mahai on 2018/12/21.
 * 登录、注册
 *
 */

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const gravatar = require('gravatar');
const jwt = require('jsonwebtoken');
const keys = require('../../config/db');
const passport = require('passport');

const User = require('../../models/User');



//$rote GET api/users
// @desc 返回请求的json数据
// @access public
router.get('/',(req,res)=> {
    res.json([
        {
            title: '注册',
            api: 'api/user/register',
            post: 'post',
            param: {
                password: '密码，必填',
                username:'账号，必填',
            }
        },
        {
            title: '登录接口',
            api: 'api/user/login',
            post: 'post',
            param: {
                password: '密码，必填',
                username: '用户名，必填',
            },
            desc: '登录接口返回的是token'
        },
        {
            title: '当前用户信息',
            api: 'api/user/current',
            post: 'get',
        },
        {
            title: '修改前验校验密码是否正确',
            api: 'api/user/compare',
            post: 'post',
            param: {
                id: '用户的id',
                password: '密码，必填',
                newpassword: '新密码，必填',
            },
            Header: '头部验证 Header：{Authorization:toen字段}'
        },
        {
            title: '修改用户信息',
            api: 'api/user/edit/:id',
            post: 'put',
            param: {
                id: '用户的id, 必填',
                avatar: '头像',
                email:'邮箱',
                firstName: '姓',
                lastName: '名',
	            role:'角色，[]'
            },
            Header: '头部验证 Header：{Authorization:toen字段}'
        },
        {
            title: '根据id获取用户信息',
            api: 'api/user/find/:id',
            post: 'get'
        },
    ])
})
//$rote POST api/users/register
// @desc 返回请求的json数据
// @access public
router.post('/register',(req,res)=>{
    //查询数据库中是否有用户
    User.findOne({username:req.body.username}).then(user=>{
        if(user){
            return res.status(400).json({
                msg:'用户已注册！',
                status:0
            })
        } else {
            let avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});
            if(req.body.avatar){
                avatar = req.body.avatar
            }
            const newUser = new User({
                username:req.body.username,
                avatar,
                password:req.body.password,
            });
            //密码加密 使用 bcryptjs
            bcrypt.genSalt(10, function(err, salt) {
                bcrypt.hash(newUser.password, salt, (err, hash)=> {
                    if(err)  throw err;
                    newUser.password = hash;
                    newUser.save().then(user=> res.json(user)).catch(err=>console.log(err))
                });
            });
        }
    });
});



router.post('/signout',passport.authenticate('jwt',{session:false}),(req,res)=>{

})

//$rote POST api/users/login
// 登录接口
// @desc 返回 token jwt passport
// @access public
router.post('/login',(req,res)=>{
    const username = req.body.username;
    const password = req.body.password;
    //查询数据库
    User.findOne({username}).then(user=>{
        if(!user){
            return res.status(404).json({
                msg:'用户不存在！',
                status:0
            });
        }
        // 密码匹配
        bcrypt.compare(password,user.password).then(isMath =>{
            if(isMath){
                // jwt.sign("规则","加密名字",'过期时间','箭头函数')
                const rule = {
                    id:user.id,
                    username:user.username
                };
                jwt.sign(rule,keys.secretOrKey,{expiresIn:33600},(err,token)=>{
                    if(err) throw err;
                    res.json({
                        success:true,
                        token:'Bearer '+token
                    });
                });
            } else {
                return res.status(400).json({
                    success:false,
                    msg:'登录失败'
                })
            }
        })
    })
});

/**
 * $rote GET api/users/current
 * 根据用户登录的token获取用户信息
 * @desc 返回 用户信息
 * @access Private
 * 第二个参数验证token
 * status:0、1、2                 0：失败 1：没有数据 2：成功
 */
router.get('/current',passport.authenticate('jwt',{session:false}),(req,res)=>{
    res.json({
        id:req.user.id,
        data:req.user.data,
        lastName:req.user.lastName,
        email:req.user.email,
        avatar:req.user.avatar,
        password:req.user.password,
        firstName:req.user.firstName,
        username: req.user.username,
        role:req.user.role
    })
});

/**
 * $rote GET api/users/compare
 * 修改密码前校验校验密码是否正确
 * param ：{id:用户id，password：原密码，newpassword：修改后的密码}
 * @access Private
 * 头部验证 Header：{Authorization:toen字段}
 */
router.post('/compare',passport.authenticate('jwt',{session:false}),(req,res)=>{
    const id = req.body.id;
    const password = req.body.password;
    const newpassword = req.body.newpassword;

    //查询数据库
    User.findOne({_id:id}).then(user=>{
        if(!user){
            return res.json({
                status:1,   //请求失败
                msg:'该用户不存在'
            });
        }
        // 密码匹配
        bcrypt.compare(password,user.password).then(isMath =>{
            //匹配成功 可以修改密码
            if(isMath){
                //密码加密 使用 bcryptjs
                bcrypt.genSalt(10, function(err, salt) {
                    bcrypt.hash(newpassword, salt, (err, hash)=> {
                        if(err)  throw err;
                        User.findOneAndUpdate(
                            {_id:id},
                            {$set:{password:hash}},
                            {new:true}
                        ).then(upUser => {
                            res.json({
                                data:upUser,
                                status:2
                            })
                        }).catch(err=>res.status(404).json({
                            msg:'修改密码失败',
                            status:1
                        }))
                    });
                });
            } else {
                res.json({
                    status:0,
                    msg:'密码匹配不正确'
                })
            }
        })
    })
})

/**
 * $rote GET api/users/edit
 * 修改用户信息
 * param ：{id:用户id，avatar：头像，name：名称}
 * @access Private
 * 头部验证 Header：{Authorization:toen字段}
 */

 router.put('/edit/:id',passport.authenticate('jwt',{session:false}),(req,res)=>{
    const id = req.params.id;
    const userInfo = {};
    if(req.body.avatar) userInfo.avatar = req.body.avatar;
    if(req.body.firstName) userInfo.firstName = req.body.firstName;
    if(req.body.lastName) userInfo.name = req.body.lastName;
    if(req.body.email) userInfo.email = req.body.email;
	 if(req.body.role) userInfo.role = req.body.role;
    //查询数据库
    User.findOne({_id:id}).then(user=>{
        if(!user){
            return res.json({
                status:1,   //请求失败
                msg:'该用户不存在'
            });
        }
        User.findOneAndUpdate(
            {_id:id},
            {$set:userInfo},
            {new:true}
        ).then(upUser => {
            res.json({
                data:upUser,
                status:2
            })
        }).catch(err=>res.status(404).json({
            msg:'更新用户信息失败',
            status:1
        }))
    })
})


/**
 * $rote GET api/users/find/:id
 * 根据id获取用户信息
 */
router.get('/find/:id',(req,res)=>{
    const id = req.params.id;

    //查询数据库
    User.findOne({_id:id}).then(user=>{
        if(!user){
            return res.json({
                status:1,   //请求失败
                msg:'该用户不存在'
            });
        } else {
            let userInfo = {
                id:user._id,
                lastName:user.lastName,
                email:user.email,
                avatar:user.avatar,
                username:user.username,
                role:user.role
            }
            res.json({
                data:userInfo,
                status:2
            })
        }
    }).catch(err=>res.status(404).json({
        msg:err,
        status:1
    }))
})

/**
 * $rote GET api/users/userlist
 * 获取用户列表
 * rows：一页显示的数据
 * page：分页
 * startTime ：开始日期 ‘2017-01-09‘ 格式 (包含开始日期)
 * endTime ：结束日期日期   (不包含结束日期)
 */
 router.get('/list',(req,res)=>{
    let userObj = {};

    if(req.query.startTime && req.query.endTime) {
        userObj['date'] = {
            "$gte" :new Date(req.query.startTime +"T00:00:00Z"),
            "$lte" :new Date(req.query.endTime + "T00:00:00Z")
        }
    }
    //分页
    if(req.query.page && req.query.rows){
        let page = parseInt(req.query.page) === 0 ? 1:parseInt(req.query.page);
        let rows = parseInt(req.query.rows);
        let count=0;
        let skip=0;
        let limit = 0;
        if(page <= 1){
            skip =0;
        } else {
            skip = rows*page - rows
        }
        User.find(userObj).then(isUser=> {
            if(!isUser){
                isUser.length = 0;
            }
            count = isUser.length;
        }).then(()=>{
            //总页数 大于当前页数
            if(Math.ceil(count/rows) >= page){
                if(Math.ceil(count/rows) == page){
                    limit = count
                } else {
                    limit = parseInt(rows)
                }
            } else {
                return res.json({
                    data:null,
                    msg:'查询不到数据',
                    status:1
                });
            }
            User.find(userObj).skip(skip).limit(limit).sort({date:-1}).then(userlist=>{
                if(!userlist){
                    return res.status(404).json({
                        data:[],
                        toatl:0,
                        page:page,
                        status:0
                    });
                }
                let userList = [];
                if(userlist.length>0){
                    userlist.map(item=>{
                        userList.push({
                            id:item._id,
                            role:item.role,
                            username:item.username,
                            lastName:item.lastName,
                            firstName:item.firstName,
                            email:item.email,
                            avatar:item.avatar,
                            date:item.date
                        })
                    })
                }
                res.json({
                    data:userList,
                    toatl:count,
                    page:page,
                    status:2
                })
            }).catch(err=>console.log(err))
        })
    } else {
        //获取所有用户
        User.find(userObj).sort({date:-1}).then(userlist=>{
            if(!userlist){
                return res.status(404).json({
                    data:[],
                    status:0
                });
            }
            let userList = [];
            if(userlist.length>0){
                userlist.map(item=>{
                    userList.push({
                        id:item._id,
                        role:item.role,
                        username:item.username,
                        lastName:item.lastName,
                        firstName:item.firstName,
                        email:item.email,
                        avatar:item.avatar,
                        date:item.date
                    })
                })
            }
            res.json({
                data:userList,
                status:2
            })
        }).catch(err=>console.log(err))
    }
})


module.exports = router;
